const WEATHER_KEY = '22204c3349f9404999ad48dfc7b193f3';
const NEWS_KEY = '5bafc55f72c293c46ca62c6ece6a0bbb'; // 新闻

export const getNewsList = async type => {
  const url = 'http://v.juhe.cn/toutiao/index';
  try {
    const response = await (
      await fetch(`${url}?key=${NEWS_KEY}&type=${type}`)
    ).json();
    if (response.error_code === 0) {
      return response.result.data;
    } else {
      return [];
    }
  } catch (error) {
    console.log('Fetch  error');
  }
};

// 获取城市信息
export const getCityInfo = async coords => {
  const url = 'https://geoapi.qweather.com/v2/city/lookup';
  try {
    const response = await (
      await fetch(
        `${url}?key=${WEATHER_KEY}&location=${coords.longitude},${coords.latitude}`,
      )
    ).json();
    if (response.code === '200') {
      return response.location[0];
    } else {
      return {};
    }
  } catch (error) {
    console.log('Fetch  error');
  }
};

// 获取三天天气预报
export const getThreeDays = async coords => {
  const url = 'https://devapi.qweather.com/v7/weather/3d';
  try {
    const response = await (
      await fetch(
        `${url}?key=${WEATHER_KEY}&location=${coords.longitude},${coords.latitude}`,
      )
    ).json();
    if (response.code === '200') {
      return response.daily;
    } else {
      return [];
    }
  } catch (error) {
    console.log('Fetch  error');
  }
};

// 获取天气指数
export const getWeatherIndices = async (coords, type = 0) => {
  const url = 'https://devapi.qweather.com/v7/indices/1d';
  try {
    const response = await (
      await fetch(
        `${url}?key=${WEATHER_KEY}&location=${coords.longitude},${coords.latitude}&type=${type}`,
      )
    ).json();
    if (response.code === '200') {
      return response.daily;
    } else {
      return [];
    }
  } catch (error) {
    console.log('Fetch  error');
  }
};
